/*
 * @Author: xiehangyun 
 * @Date: 2025-05-15 10:42:14 
 * @Last Modified by: xiehangyun
 * @Last Modified time: 2025-05-15 11:10:52
 */
import { Button } from "@nutui/nutui-react-taro";
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { ReactNode, useEffect, useState } from 'react';
import addressManageStore from '../addressManageStore';
import styles from './bottomBtns.module.less';
import { autorun, toJS } from "mobx";

interface Iprops {
    children?: ReactNode
}

const BottomBtns = (props: Iprops) => {

    const [list, addAddress] = useState(toJS(addressManageStore.list));

    useEffect(() => autorun(() => {
        addAddress(toJS(addressManageStore.list));
    }, { delay: 30 }), []);


    const handleImportFromWeChat = async () => {
        try {
            const res: any = await Taro.chooseAddress();
            console.log("从微信导入的地址:", res);
            if (res.errMsg === "chooseAddress:ok") {
                addressManageStore.add({
                    userName: res.userName,           // 收货人姓名
                    postalCode: res.postalCode,         // 邮编
                    province: res.provinceName,           // 省
                    city: res.cityName,               // 市
                    county: res.countyName,             // 区
                    detail: res.detailInfo,             // 详细地址
                    nationalCode: res.nationalCode,       // 国家码
                    phone: res.telNumber,              // 手机号码
                    ifDefault: false          // 是否默认地址
                });

            }
            // 在这里处理导入的地址数据，例如保存到状态或发送到服务器
        } catch (error) {
            console.error("导入微信地址失败:", error);
        }
    };

    const handleCreateNewAddress = () => {
        console.log("新建地址");
        // 在这里添加新建地址的逻辑
        Taro.navigateTo({
            url: "/subPages/NewAddressManage/NewAddressManage"
        });
    };

    return (
        <View className={styles.bottomBtns}>
            {list.length >= 10 ? (
                <View className={styles.message}>地址最多添加10条</View>
            ) : (
                <>
                    <Button type="success" onClick={handleImportFromWeChat} className={styles.leftBtn}>
                        {/* 微信图标 */}
                        <text className={`${styles.wechatIcon} iconfont icon-wechat`}></text>
                        从微信导入地址
                    </Button>
                    <Button type="primary" onClick={handleCreateNewAddress} className={styles.rightBtn}>
                        新建地址
                    </Button>
                </>
            )}
        </View>
    );
};

export default BottomBtns;